package com.ease.component.util {

   import com.ease.component.constant.StringConstant;
   import com.ease.component.events.AdvancedMouseEvent;

   import flash.display.DisplayObject;
   import flash.events.EventDispatcher;
   import flash.events.IEventDispatcher;
   import flash.events.MouseEvent;
   import flash.utils.getQualifiedClassName;

   import mx.controls.listClasses.IDropInListItemRenderer;
   import mx.core.IDataRenderer;

   [Exclude(name = "activate", kind = "event")]
   [Exclude(name = "deactivate", kind = "event")]
   [ResourceBundle("widgets")]
   public class ListRightClickAdapterBase extends EventDispatcher {
      private var _target:IEventDispatcher;

      public function ListRightClickAdapterBase(self:ListRightClickAdapterBase) {
         super();
         if (self != this) {
            throw new Error("Cannot instantiate class " + getQualifiedClassName(this) );
         }
      }

      protected function getItem(object:DisplayObject):Object {
         for (; object != target; object = object.parent) {
            if (object is IDropInListItemRenderer && object is IDataRenderer) {
               var renderer:IDropInListItemRenderer = IDropInListItemRenderer(object);
               if (renderer.listData && renderer.listData.owner == target) {
                  return IDataRenderer(object).data;
               }
            }
         }
         return null;
      }

      private function handleRightClick(event:MouseEvent):void {
         if (!event.ctrlKey) {
            var item:Object = getItem(DisplayObject(event.target));
            if (!item || !isSelected(item)) {
               setSelectedItem(item);
            }
         }
      }

      protected function isRowSelected(rowIndex:int):Boolean {
         return false;
      }

      protected function isSelected(item:Object):Boolean {
         return false;
      }

      protected function setSelectedItem(item:Object):void {
      }

      protected function get target():IEventDispatcher {
         return _target;
      }

      /**
       * @private
       */
      protected function set target(value:IEventDispatcher):void {
         if (_target != value) {
            if (_target) {
               _target.removeEventListener(AdvancedMouseEvent.RIGHT_MOUSE_DOWN, handleRightClick);
            }
            _target = value;
            if (value) {
               value.addEventListener(AdvancedMouseEvent.RIGHT_MOUSE_DOWN, handleRightClick, false, 0, true);
            }
         }
      }
   }
}
